import api from '@/store/api';

let oemInfo = '';
const ChassisStore = {
  namespaced: true,
  state: {
    chassis: [],
    chassisHealth: [],
    fanInfo: [],
    metricsInfo: [],
    fanControlMode: '',
    fanSmartCooling: {},
    diskBackplaneInfo: [],
    onBackplaneDiskInfo: [],
    m2DiskInfo: [],
    onBoardDiskInfo: [],
    systemsPowerInfo: [],
    totalPower: 'N/A',
    pcieDeviceInfo: [],
    powerConsumption: [],
    totalPowerAlarm: [],
    serverStatus: null,
    blinkStatus: false,
    uidSwitchStatus: false,
    uidStatus: null,
    biosPostComplete: false,
    driverPresentNum: 0,
    overviewData: {},
    accountRoles: [],
    leakageInfo: [],
    cpuSubsystemRange: null,
    entirePlatformRange: null
  },
  getters: {
    biosPostComplete: (state) => state.biosPostComplete,
    chassis: (state) => state.chassis,
    chassisHealth: (state) => state.chassisHealth,
    fanInfo: (state) => state.fanInfo,
    metricsInfo: (state) => state.metricsInfo,
    fanControlMode: (state) => state.fanControlMode,
    fanSmartCooling: (state) => state.fanSmartCooling,
    diskBackplaneInfo: (state) => state.diskBackplaneInfo,
    onBackplaneDiskInfo: (state) => state.onBackplaneDiskInfo,
    onBoardDiskInfo: (state) => state.onBoardDiskInfo,
    m2DiskInfo: (state) => state.m2DiskInfo,
    systemsPowerInfo: (state) => state.systemsPowerInfo,
    totalPower: (state) => state.totalPower,
    pcieDeviceInfo: (state) => state.pcieDeviceInfo,
    powerConsumption: (state) => state.powerConsumption,
    totalPowerAlarm: (state) => state.totalPowerAlarm,
    serverStatus: (state) => state.serverStatus,
    uidStatus: (state) => {
      if (state.blinkStatus) {
        state.uidStatus = 'Blinking';
      } else {
        if (state.uidSwitchStatus) {
          state.uidStatus = 'Lit';
        } else {
          state.uidStatus = 'Off';
        }
      }
      return state.uidStatus;
    },
    driverPresentNum: (state) => state.driverPresentNum,
    overviewData: (state) => state.overviewData,
    accountRoles(state) {
      return state.accountRoles;
    },
    leakageInfo: (state) => state.leakageInfo
  },
  mutations: {
    setBiosPostComplete: (state, data) => {
      if (data == 'Standby' || data != 'Inactive') {
        state.biosPostComplete = true;
      } else {
        state.biosPostComplete = false;
      }
    }, //判断bios 是否post完成，完成为true。
    setChassisInfo: (state, data) => (state.chassis = data),
    setChassisHealthInfo: (state, data) => (state.chassisHealth = data),
    setFanInfo: (state, data) => (state.fanInfo = data),
    setMetricsInfo: (state, data) => (state.metricsInfo = data),
    setFanControlMode: (state, data) => (state.fanControlMode = data),
    setFanSmartCooling: (state, data) => (state.fanSmartCooling = data),
    setTotalPower: (state, data) => (state.totalPower = data),
    setPowerConsumption: (state, data) => (state.powerConsumption = data),
    setTotalPowerAlarm: (state, data) => (state.totalPowerAlarm = data),
    setDiskBackplaneInfo: (state, data) => {
      var backplaneobjArray = [];
      for (const backplaneobj of data) {
        const diskBackplaneInfo = {};
        diskBackplaneInfo.front_rear = backplaneobj.Type; //接口新增字段Type
        // diskBackplaneInfo.backplane_id = backplaneobj.Id;
        if (backplaneobj.Name.indexOf('HDD_') >= 0) {
          diskBackplaneInfo.backplane_id = backplaneobj.Name.split('_BP')[1];
        }
        diskBackplaneInfo.present = backplaneobj.Status.State;
        diskBackplaneInfo.cpld_version = backplaneobj.BackplaneVersion;
        // key中含有特殊字符
        diskBackplaneInfo.port_number = backplaneobj.PortCount;
        diskBackplaneInfo.hdd_number = backplaneobj.Drives.length;
        diskBackplaneInfo.temp = backplaneobj.Temperature;

        backplaneobjArray.push(diskBackplaneInfo);
      }
      state.diskBackplaneInfo = backplaneobjArray;
    },
    setDiskinfo: (state, data) => {
      var onBoardDiskobjArray = [];
      var onBackplaneDiskobjArray = [];
      var m2DiskobjArray = [];
      let index = 0;
      for (const diskobj of data) {
        //前置
        if (-1 != diskobj.Id.indexOf('FP')) {
          const onFrontBackplaneDiskInfo = {};
          onFrontBackplaneDiskInfo.front_rear = 'Front';
          onFrontBackplaneDiskInfo.id = index;
          onFrontBackplaneDiskInfo.present = diskobj.Status.State;
          // onFrontBackplaneDiskInfo.speed = diskobj.CapableSpeedGbs; //接口速率
          if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
            if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
              onFrontBackplaneDiskInfo.error =
                diskobj.Oem[`${oemInfo}`].ErrorStatus == true
                  ? 'Enabled'
                  : 'Disabled';
              onFrontBackplaneDiskInfo.rebuild =
                diskobj.Oem[`${oemInfo}`].RebuildStatus == true
                  ? 'Enabled'
                  : 'Disabled';
            }
          }
          onFrontBackplaneDiskInfo.location = diskobj.Location[0].Info;
          if (diskobj.Protocol == 'NVMe') {
            onFrontBackplaneDiskInfo.nvme = 'Enabled';
            onFrontBackplaneDiskInfo.noExpand = false;
            onFrontBackplaneDiskInfo.backplaneId = diskobj.Id;
            onFrontBackplaneDiskInfo.manufacturer = diskobj.Manufacturer;
            onFrontBackplaneDiskInfo.mediaType = diskobj.MediaType;
            onFrontBackplaneDiskInfo.model = diskobj.ModuleNumber;
            onFrontBackplaneDiskInfo.capacity = diskobj.CapacityBytes;
            if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
              if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
                onFrontBackplaneDiskInfo.interfaceType =
                  diskobj.Oem[`${oemInfo}`].InterfaceType;
                onFrontBackplaneDiskInfo.lifeLeft =
                  diskobj.Oem[`${oemInfo}`].PredictedMediaLifeLeftPercent;
              }
            }
            onFrontBackplaneDiskInfo.firmwareVersion = diskobj.Revision;
            onFrontBackplaneDiskInfo.sn = diskobj.SerialNumber;
          } else {
            onFrontBackplaneDiskInfo.nvme = 'Disabled';
            onFrontBackplaneDiskInfo.noExpand = true;
          }

          if (diskobj.IndicatorLED == 'Lit') {
            onFrontBackplaneDiskInfo.indicatorLED = true;
          } else {
            onFrontBackplaneDiskInfo.indicatorLED = false;
          }
          onFrontBackplaneDiskInfo.diskid = diskobj.Id;

          onBackplaneDiskobjArray.push(onFrontBackplaneDiskInfo);
          index++;
          //后置
        } else if (-1 != diskobj.Id.indexOf('RP')) {
          const onRearBackplaneDiskInfo = {};
          onRearBackplaneDiskInfo.front_rear = 'Rear';
          onRearBackplaneDiskInfo.id = index;
          onRearBackplaneDiskInfo.present = diskobj.Status.State;
          // onRearBackplaneDiskInfo.speed = diskobj.CapableSpeedGbs;
          if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
            if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
              onRearBackplaneDiskInfo.error =
                diskobj.Oem[`${oemInfo}`].ErrorStatus == true
                  ? 'Enabled'
                  : 'Disabled';
              onRearBackplaneDiskInfo.rebuild =
                diskobj.Oem[`${oemInfo}`].RebuildStatus == true
                  ? 'Enabled'
                  : 'Disabled';
            }
          }
          onRearBackplaneDiskInfo.location = diskobj.Location[0].Info;
          if (diskobj.Protocol == 'NVMe') {
            onRearBackplaneDiskInfo.nvme = 'Enabled';
            onRearBackplaneDiskInfo.noExpand = false;
            onRearBackplaneDiskInfo.backplaneId = diskobj.Id;
            onRearBackplaneDiskInfo.manufacturer = diskobj.Manufacturer;
            onRearBackplaneDiskInfo.mediaType = diskobj.MediaType;
            onRearBackplaneDiskInfo.model = diskobj.ModuleNumber;
            onRearBackplaneDiskInfo.capacity = diskobj.CapacityBytes;
            if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
              if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
                onRearBackplaneDiskInfo.interfaceType =
                  diskobj.Oem[`${oemInfo}`].InterfaceType;
                onRearBackplaneDiskInfo.lifeLeft =
                  diskobj.Oem[`${oemInfo}`].PredictedMediaLifeLeftPercent;
              }
            }
            onRearBackplaneDiskInfo.firmwareVersion = diskobj.Revision;
            onRearBackplaneDiskInfo.sn = diskobj.SerialNumber;
          } else {
            onRearBackplaneDiskInfo.nvme = 'Disabled';
            onRearBackplaneDiskInfo.noExpand = true;
          }

          if (diskobj.IndicatorLED == 'Lit') {
            onRearBackplaneDiskInfo.indicatorLED = true;
          } else {
            onRearBackplaneDiskInfo.indicatorLED = false;
          }
          onRearBackplaneDiskInfo.diskid = diskobj.Id;

          onBackplaneDiskobjArray.push(onRearBackplaneDiskInfo);
          index++;
          //内置
        } else if (-1 != diskobj.Id.indexOf('IP')) {
          const onInnerBackplaneDiskInfo = {};
          onInnerBackplaneDiskInfo.front_rear = 'Inner';
          onInnerBackplaneDiskInfo.id = index;
          onInnerBackplaneDiskInfo.present = diskobj.Status.State;
          // onInnerBackplaneDiskInfo.speed = diskobj.CapableSpeedGbs;
          if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
            if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
              onInnerBackplaneDiskInfo.error =
                diskobj.Oem[`${oemInfo}`].ErrorStatus == true
                  ? 'Enabled'
                  : 'Disabled';
              onInnerBackplaneDiskInfo.rebuild =
                diskobj.Oem[`${oemInfo}`].RebuildStatus == true
                  ? 'Enabled'
                  : 'Disabled';
            }
          }
          onInnerBackplaneDiskInfo.location = diskobj.Location[0].Info;
          if (diskobj.Protocol == 'NVMe') {
            onInnerBackplaneDiskInfo.nvme = 'Enabled';
            onInnerBackplaneDiskInfo.noExpand = false;
            onInnerBackplaneDiskInfo.backplaneId = diskobj.Id;
            onInnerBackplaneDiskInfo.manufacturer = diskobj.Manufacturer;
            onInnerBackplaneDiskInfo.mediaType = diskobj.MediaType;
            onInnerBackplaneDiskInfo.model = diskobj.ModuleNumber;
            onInnerBackplaneDiskInfo.capacity = diskobj.CapacityBytes;
            if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
              if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
                onInnerBackplaneDiskInfo.interfaceType =
                  diskobj.Oem[`${oemInfo}`].InterfaceType;
                onInnerBackplaneDiskInfo.lifeLeft =
                  diskobj.Oem[`${oemInfo}`].PredictedMediaLifeLeftPercent;
              }
            }
            onInnerBackplaneDiskInfo.firmwareVersion = diskobj.Revision;
            onInnerBackplaneDiskInfo.sn = diskobj.SerialNumber;
          } else {
            onInnerBackplaneDiskInfo.nvme = 'Disabled';
            onInnerBackplaneDiskInfo.noExpand = true;
          }

          if (diskobj.IndicatorLED == 'Lit') {
            onInnerBackplaneDiskInfo.indicatorLED = true;
          } else {
            onInnerBackplaneDiskInfo.indicatorLED = false;
          }
          onInnerBackplaneDiskInfo.diskid = diskobj.Id;

          onBackplaneDiskobjArray.push(onInnerBackplaneDiskInfo);
          index++;
        } else if (-1 != diskobj.Id.indexOf('OB')) {
          const onBoardDiskInfo = {};
          onBoardDiskInfo.location = diskobj.Location[0].Info;
          onBoardDiskInfo.present = diskobj.Status.State;
          onBoardDiskInfo.capacityGB =
            diskobj.CapacityBytes / 1024 / 1024 / 1024;
          onBoardDiskInfo.model = diskobj.ModuleNumber;
          onBoardDiskInfo.sn = diskobj.SerialNumber;
          onBoardDiskInfo.capable_speed = diskobj.CapableSpeedGbs;

          onBoardDiskobjArray.push(onBoardDiskInfo);
        } else if (-1 != diskobj.Id.indexOf('HDM')) {
          const m2DiskInfo = {};
          m2DiskInfo.id = index; //序号
          m2DiskInfo.present = diskobj.Status.State; //在位
          m2DiskInfo.location = diskobj.Location[0].Info; //位置
          if (diskobj.Protocol == 'NVMe') {
            m2DiskInfo.nvme = 'Enabled'; //nvme
            m2DiskInfo.noExpand = false;
            m2DiskInfo.backplaneId = diskobj.Id; //背板序号
            m2DiskInfo.manufacturer = diskobj.Manufacturer; //硬盘厂家
            m2DiskInfo.mediaType = diskobj.MediaType; //介质类型
            m2DiskInfo.model = diskobj.ModuleNumber; //型号
            m2DiskInfo.capacity = diskobj.CapacityBytes; //容量(GiB)
            if (Object.prototype.hasOwnProperty.call(diskobj, 'Oem')) {
              if (Object.prototype.hasOwnProperty.call(diskobj.Oem, oemInfo)) {
                m2DiskInfo.interfaceType =
                  diskobj.Oem[`${oemInfo}`].InterfaceType; //接口类型
                m2DiskInfo.lifeLeft =
                  diskobj.Oem[`${oemInfo}`].PredictedMediaLifeLeftPercent; //剩余寿命
              }
            }
            m2DiskInfo.firmwareVersion = diskobj.Revision; //固件版本
            m2DiskInfo.sn = diskobj.SerialNumber; //序列号
          } else {
            m2DiskInfo.nvme = 'Disabled'; //nvme
            m2DiskInfo.noExpand = true;
          }
          m2DiskInfo.diskid = diskobj.Id;

          m2DiskobjArray.push(m2DiskInfo);
          index++;
        }
        state.onBackplaneDiskInfo = onBackplaneDiskobjArray;
        state.onBoardDiskInfo = onBoardDiskobjArray;
        state.m2DiskInfo = m2DiskobjArray;
      }
    },
    setSystemPowerInfo: (state, data) => {
      let powerobjArray = [];
      for (let i = 0; i < data.PowerSupplies.length; i++) {
        const systemPowerInfo = {};
        systemPowerInfo.id = data.PowerSupplies[i].MemberId;
        systemPowerInfo.present = data.PowerSupplies[i].Status.State;
        systemPowerInfo.health = data.PowerSupplies[i].Status.Health;
        systemPowerInfo.vendor = data.PowerSupplies[i].Manufacturer;
        systemPowerInfo.model = data.PowerSupplies[i].Model;
        systemPowerInfo.sn = data.PowerSupplies[i].SerialNumber;
        systemPowerInfo.Pout = data.PowerSupplies[i].LastPowerOutputWatts;
        systemPowerInfo.rated_power = data.PowerSupplies[i].PowerCapacityWatts;
        systemPowerInfo.Vin = data.PowerSupplies[i].LineInputVoltage;
        systemPowerInfo.firmware_version =
          data.PowerSupplies[i].FirmwareVersion;
        systemPowerInfo.input_type = data.PowerSupplies[i].PowerSupplyType;
        // systemPowerInfo.env_temperature =
        //   data.PowerSupplies[i].Oem[`${oemInfo}`].EnvironmentTemperature; // G8
        if (
          Object.prototype.hasOwnProperty.call(data.PowerSupplies[i], 'Oem')
        ) {
          if (
            Object.prototype.hasOwnProperty.call(
              data.PowerSupplies[i].Oem,
              oemInfo
            )
          ) {
            // systemPowerInfo.temperature =
            // data.PowerSupplies[i].Oem[`${oemInfo}`].Temperature; // M7
            systemPowerInfo.temperature =
              data.PowerSupplies[i].Oem[`${oemInfo}`].EnvironmentTemperature; // G8
            systemPowerInfo.Pin =
              data.PowerSupplies[i].Oem[`${oemInfo}`].InputPower;
            systemPowerInfo.Vout =
              data.PowerSupplies[i].Oem[`${oemInfo}`].OutputVolt;
            systemPowerInfo.Iin =
              data.PowerSupplies[i].Oem[`${oemInfo}`].InputCurrent;
            systemPowerInfo.Iout =
              data.PowerSupplies[i].Oem[`${oemInfo}`].OutputCurrent;
            systemPowerInfo.pri_temperature =
              data.PowerSupplies[i].Oem[`${oemInfo}`].PrimarySideTemperature;
            systemPowerInfo.sec_temperature =
              data.PowerSupplies[i].Oem[`${oemInfo}`].SecondarySideTemperature;
            systemPowerInfo.work_mode =
              data.PowerSupplies[i].Oem[`${oemInfo}`].WorkMode; //改为字段显示text，不用下拉栏了
          }
        }
        powerobjArray.push(systemPowerInfo);
      }
      state.systemsPowerInfo = powerobjArray;
    },
    setPCIeDeviceInfo: (state, data) => {
      let pcieDeviceobjArray = [];
      let index = 0;
      for (const pciedeviceobj of data) {
        const pcieDeviceInfo = {};
        pcieDeviceInfo.id = index; //add by lim 20230804 表格展开expand是根据row.id，将数据增加id
        pcieDeviceInfo.number = pciedeviceobj.data.Id;
        pcieDeviceInfo.location = pciedeviceobj.data.Oem[`${oemInfo}`].Location;
        pcieDeviceInfo.present = pciedeviceobj.data.Status.State;
        pcieDeviceInfo.device_type =
          pciedeviceobj.data.Oem[`${oemInfo}`].DeviceClass;
        pcieDeviceInfo.device_name = pciedeviceobj.data.Model;
        pcieDeviceInfo.vendor = pciedeviceobj.data.Manufacturer;
        pcieDeviceInfo.rated_bandwidth =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].LinkWidthAbility;
        pcieDeviceInfo.rated_speed =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].LinkSpeedAbility;
        pcieDeviceInfo.current_bandwidth =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].LinkWidth;
        pcieDeviceInfo.current_speed =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].LinkSpeed;
        pcieDeviceInfo.device_BDF =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].DeviceBDF;
        pcieDeviceInfo.root_port_BDF =
          pciedeviceobj.data.PCIeFunc.Oem[`${oemInfo}`].RootPortBDF;
        pcieDeviceInfo.deviceId = pciedeviceobj.data.PCIeFunc.DeviceId;
        pcieDeviceInfo.subsystemId = pciedeviceobj.data.PCIeFunc.SubsystemId;
        pcieDeviceInfo.vendorId = pciedeviceobj.data.PCIeFunc.VendorId;
        pcieDeviceInfo.subsystemVendorId =
          pciedeviceobj.data.PCIeFunc.SubsystemVendorId;
        index++;
        pcieDeviceobjArray.push(pcieDeviceInfo);
      }
      state.pcieDeviceInfo = pcieDeviceobjArray;
    },
    setServerStatus: (state, serverStatus) =>
      (state.serverStatus = serverStatus),
    setBlinkStatus: (state, status) => (state.blinkStatus = status),
    SetUidSwitchStatus: (state, status) => (state.uidSwitchStatus = status),
    setDriverPresentNum: (state, data) => (state.driverPresentNum = data),
    setOverviewData: (state, data) => (state.overviewData = data),
    setAccountRoles(state, accountRoles) {
      state.accountRoles = accountRoles;
    },
    setLeakageInfo: (state, data) => {
      const leakage = {};
      leakage.leakLine = data.LeakLineStatus;
      leakage.leakagePolicy = data.PowerPolicy;
      state.leakageInfo = [leakage];
    },
    setCpuSubsystemRange: (state, data) => (state.cpuSubsystemRange = data),
    setEntirePlatformRange: (state, data) => (state.entirePlatformRange = data)
  },
  actions: {
    async getChassisInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id)
        .then((response) => {
          commit('setChassisInfo', response.data);
          if (response.data.PowerState == 'On') {
            commit('setServerStatus', 'Running');
          } else {
            commit('setServerStatus', 'Off');
          }
        })
        .catch(() => {});
    },
    async getChassisHealthInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/HealthSummary')
        .then(({ data }) => commit('setChassisHealthInfo', data))
        .catch(() => {});
    },
    setPowerStatus({ dispatch }, { redfishField, datas }) {
      let redfish_id = redfishField.redfish_id;
      let data = { ResetType: datas };
      let inittmout = 3000;
      if (datas == 'PowerCycle' || datas == 'ForceOff') {
        inittmout = 5000; //for power cycle we check if host is powered on again after 5 secs
      } else if (datas == 'GracefulShutdown') {
        //软关机时间长，设置为15s
        inittmout = 15000;
      } else {
        inittmout = 2000;
      }
      return api
        .post(
          '/redfish/v1/Chassis/' + redfish_id + '/Actions/Chassis.Reset',
          data
        )
        .then(() => {
          setTimeout(() => {
            dispatch('getChassisInfo', redfishField);
          }, inittmout);
        })
        .catch((error) => {
          dispatch('getChassisInfo', redfishField);
          throw new Error(error);
        });
    },
    async setPowerMode({ dispatch }, { datas }) {
      let redfish_id = datas.redfishField.redfish_id;
      let data = datas.datas;
      return await api
        .patch('/redfish/v1/Chassis/' + redfish_id + '/Power', data)
        .then(() => {
          dispatch('getSystemPowerInfo', datas.redfishField);
        })
        .catch((error) => {
          dispatch('getSystemPowerInfo', datas.redfishField);
          throw new Error(error);
        });
    },
    async getFanInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      let oem_info = redfishField.oem_info;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Thermal')
        .then((response) => {
          const fanDatas = response.data.Fans.map((data) => {
            const { Name, Reading, Oem, Model, Status } = data;
            let state = Status.State;
            let status = Status.Health;
            if (state == 'Enabled') {
              state = status;
            }
            let Id = 'N/A';
            let SpeedRatio = 'N/A';
            if (Oem != undefined) {
              if (Object.prototype.hasOwnProperty.call(Oem, oem_info)) {
                Id = Oem[`${oem_info}`].FanIndex;
                SpeedRatio = Oem[`${oem_info}`].SpeedRatio;
              }
            }
            return {
              Id: Id,
              Name: Name,
              Reading: Reading,
              SpeedRatio: SpeedRatio,
              Model: Model,
              Status: state,
              State: Status.State
            };
          });
          commit(
            'setFanControlMode',
            response.data.Oem[`${oem_info}`].FanControlMode
          );
          commit(
            'setFanSmartCooling',
            response.data.Oem[`${oem_info}`].SmartCooling
          );
          // let SmartCooling = {
          //   CPUMarginTarget: 25,
          //   CPUTarget: null,
          //   CPUTjmax: null,
          //   CoolingMode: 'LowNoise',
          //   InletTempDuty: [
          //     {
          //       duty: 40,
          //       temp: 20
          //     },
          //     {
          //       duty: 60,
          //       temp: 25
          //     },
          //     {
          //       duty: 80,
          //       temp: 30
          //     },
          //     {
          //       duty: 100,
          //       temp: 35
          //     }
          //   ],
          //   SmartCooling: 'Auto'
          // };
          //commit('setFanSmartCooling', SmartCooling);

          commit('setFanInfo', fanDatas);
        });
    },
    async getTrustedMetricsInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      let oem_info = redfishField.oem_info;
      return await api
        .get('/redfish/v1/Managers/'+ redfish_id + '/Oem/' + oem_info + '/trustedMetrics')
        .then((response) => {
          commit('setMetricsInfo', response.data.TrustedMetrics);
        });
    },
    setFanCtrlMode({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfish_id.redfish_id;
      return api
        .patch(`/redfish/v1/Chassis/${redfish_id}/Thermal`, data)
        .then(() => {
          setTimeout(() => {
            dispatch('getFanInfo', datas.redfish_id);
          }, 8000); //设置8000毫秒后再查询风扇，时间短查询设置的控制模式没启作用
        })
        .catch((error) => {
          dispatch('getFanInfo', datas.redfish_id);
          throw new Error(error);
        });
    },
    setFanSpeedRatio({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfish_id.redfish_id;
      return api
        .patch(`/redfish/v1/Chassis/${redfish_id}/Thermal`, data)
        .then(() => {
          dispatch('getFanInfo', datas.redfish_id);
        })
        .catch((error) => {
          dispatch('getFanInfo', datas.redfish_id);
          throw new Error(error);
        });
    },
    async setUIDstatus({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfish_id.redfish_id;
      await dispatch('getChassisInfo', datas.redfish_id);
      return api
        .patch(`/redfish/v1/Chassis/${redfish_id}`, data)
        .then(() => {})
        .catch((error) => {
          throw new Error(error);
        });
    },
    async getDiskBackplaneInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Backplanes')
        .then((response) =>
          response.data.Members.map(
            (backplaneCollection) => backplaneCollection['@odata.id']
          )
        )
        .then((backplaneCollectionIds) =>
          api.all(backplaneCollectionIds.map((backplane) => api.get(backplane)))
        )
        .then((backplanes) => {
          const backplanesData = backplanes.map((backplane) => backplane.data);
          commit('setDiskBackplaneInfo', backplanesData);
        })
        .catch(() => {});
    },
    async getDiskInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      oemInfo = redfishField.oem_info;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Drives')
        .then((response) =>
          response.data.Members.map(
            (diskCollection) => diskCollection['@odata.id']
          )
        )
        .then((diskCollectionIds) =>
          api.all(diskCollectionIds.map((disk) => api.get(disk)))
        )
        .then((disks) => {
          const disksData = disks.map((disk) => disk.data);
          commit('setDiskinfo', disksData);
        })
        .catch(() => {});
    },
    async getDiskIdInfo(NULL, { datas }) {
      let redfish_id = datas.redfishField.redfish_id;
      let diskid = datas.diskid;

      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Drives/' + diskid)
        .then(() => {})
        .catch(() => {});
    },
    async setonBoardDiskLED({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfishField.redfish_id;
      let diskid = datas.diskid;
      return await api
        .patch(`/redfish/v1/Chassis/${redfish_id}/Drives/${diskid}`, data)
        .then(() => {
          setTimeout(() => {
            dispatch('getDiskIdInfo', { datas });
          }, 1000);
        })
        .catch((error) => {
          throw new Error(error);
        });
    },
    async getSystemPowerInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      oemInfo = redfishField.oem_info;
      let totalPower = 'N/A';
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Power')
        .then((response) => {
          commit('setSystemPowerInfo', response.data);
          if (Object.prototype.hasOwnProperty.call(response.data, 'Oem')) {
            if (
              Object.prototype.hasOwnProperty.call(response.data.Oem, oemInfo)
            ) {
              totalPower = response.data.Oem[`${oemInfo}`].TotalPower;
            }
          }
          commit('setTotalPower', totalPower);
        })
        .catch(() => {});
    },
    async getPCIeDeviceInfo({ dispatch }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      oemInfo = redfishField.oem_info;
      let pcies = [];
      await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/PCIeDevices')
        .then((response) =>
          response.data.Members.map(
            (pcieDeviceCollection) => pcieDeviceCollection['@odata.id']
          )
        )
        .then((pcieDeviceCollectionIds) =>
          api.all(
            pcieDeviceCollectionIds.map((pcieDevice) => api.get(pcieDevice))
          )
        )
        .then((pcieDevices) => {
          for (let i = 0; i < pcieDevices.length; i++) {
            pcies[i] = pcieDevices[i];
          }
        })
        .catch(() => {});
      await dispatch('getPCIeFunctions', pcies);
      //await commit('setPCIeDeviceInfo', pcies);
    },
    async getPCIeFunctions({ commit }, data) {
      for (let j = 0; j < data.length; j++) {
        let PCIeFunc = {};
        let dataPcieFunction = data[j].data.Links.PCIeFunctions.map(
          (functionCollection) => functionCollection['@odata.id']
        );
        await api
          .all(dataPcieFunction.map((pcieFunction) => api.get(pcieFunction)))
          .then((response) => {
            response.forEach((functionitems) => {
              PCIeFunc = functionitems.data;
            });
          });
        data[j].data.PCIeFunc = PCIeFunc;
      }
      await commit('setPCIeDeviceInfo', data);
    },
    async getPowerConsumptionInfo({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      let oem_info = redfishField.oem_info;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Power')
        .then((response) => {
          let alarmData = {};
          let powerLimitData = {};
          let cpuSubsystemRange = {};
          let entirePlatformRange = {};
          if (Object.prototype.hasOwnProperty.call(response.data, 'Oem')) {
            if (
              Object.prototype.hasOwnProperty.call(response.data.Oem, oem_info)
            ) {
              alarmData.WarningThreshold =
                response.data.Oem[oem_info].WarningThreshold;
              alarmData.CriticalThreshold =
                response.data.Oem[oem_info].CriticalThreshold;
              alarmData.RetainThreshold =
                response.data.Oem[oem_info].RetainThreshold;
              powerLimitData.LimitInWatts = response.data.PowerControl[0].Oem[oem_info].LimitInWatts;
              powerLimitData.PolicyState = response.data.PowerControl[0].Oem[oem_info].PolicyState;

              // cpuSubsystemRange.Max =
              //   response.data.Oem[oem_info].cpuSubsystemPowerBoundaryValue.Max;
              // cpuSubsystemRange.Min =
              //   response.data.Oem[oem_info].cpuSubsystemPowerBoundaryValue.Min;

              entirePlatformRange.Max =
                response.data.Oem[
                  oem_info
                ].entirePlatformPowerBoundaryValue.Max;
              entirePlatformRange.Min =
                response.data.Oem[
                  oem_info
                ].entirePlatformPowerBoundaryValue.Min;
            }
          }
          commit('setPowerConsumption', powerLimitData);
          commit('setTotalPowerAlarm', alarmData);
          commit('setCpuSubsystemRange', cpuSubsystemRange);
          commit('setEntirePlatformRange', entirePlatformRange);
        })
        .catch(() => {});
    },
    async setPowerLimit({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfish_id.redfish_id;
      return api
        .patch(`/redfish/v1/Chassis/${redfish_id}/Power`, data)
        .then(() => {
          setTimeout(() => {
            dispatch('getPowerConsumptionInfo', datas.redfish_id);
          }, 3000);
        })
        .catch((error) => {
          setTimeout(() => {
            dispatch('getPowerConsumptionInfo', datas.redfish_id);
          }, 3000);
          throw new Error(error);
        });
    },
    /*接口待确定后修改*/
    async delPowerLimit({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfishField.redfish_id;
      let oem_info = datas.redfishField.oem_info;
      return api
        .post(
          `/redfish/v1/Chassis/${redfish_id}/Power/Actions/Oem/${oem_info}/Power.DeletePolicy`,
          data
        )
        .then(() => {
          setTimeout(() => {
            dispatch('getPowerConsumptionInfo', datas.redfishField);
          }, 3000);
        })
        .catch((error) => {
          dispatch('getPowerConsumptionInfo', datas.redfishField);
          throw new Error(error);
        });
    },
    async getDriverPresentNum({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Drives')
        .then(({ data }) =>
          commit('setDriverPresentNum', data[`Members@odata.count`])
        )
        .catch(() => {});
    },
    async getOverviewData({ commit }) {
      return await api
        .get('/redfish/v1/OemService/Overview')
        .then(({ data }) => {
          commit('setOverviewData', data);
          if (data.PowerState == 'On') {
            commit('setServerStatus', 'Running');
          } else {
            commit('setServerStatus', 'Off');
          }
          let rolesData = [];
          let roles = data.Roles;
          Object.keys(roles).forEach((key) => {
            let role = {
              groupname: '',
              privilegeData: []
            };
            role.groupname = key;
            let assigned = roles[key].AssignedPrivileges;
            let oem = roles[key].OemPrivileges;
            let privilegeData = [];
            for (let i = 0; i < assigned.length; i++) {
              privilegeData.push(assigned[i]);
            }
            for (let j = 0; j < oem.length; j++) {
              privilegeData.push(oem[j]);
            }
            role.privilegeData = privilegeData;
            rolesData.push(role);
          });
          commit('setAccountRoles', rolesData);
        })
        .catch(() => {});
    },
    async getLeakage({ commit }, redfishField) {
      let redfish_id = redfishField.redfish_id;
      return await api
        .get('/redfish/v1/Chassis/' + redfish_id + '/Leakage')
        .then((response) => {
          commit('setLeakageInfo', response.data);
        })
        .catch(() => {});
    },
    async setLeakage({ dispatch }, { datas }) {
      let data = datas.data;
      let redfish_id = datas.redfishField.redfish_id;
      return api
        .patch(`/redfish/v1/Chassis/${redfish_id}/Leakage`, data)
        .then(() => dispatch('getLeakage', datas.redfishField))
        .catch((error) => {
          throw new Error(error);
        });
    }
  }
};

export default ChassisStore;
